﻿Imports System.Security.Principal
Imports Oracle.DataAccess.Client
Public Class CustomPrincipal
    Private Shared lUser As String
    Private Shared lPass As String
    Private Shared lRestrinASede As Boolean
    Private Shared lEsCajero As Boolean
    Private Shared lIdCaja As String
    Private Shared lIdSede As String
    Private Shared lRestrinAListaTDoc As Boolean
    Private Shared lListaTDoc As String
    Private Shared lIsAutenticado As Boolean = False
    Private Shared lRoles As String
    Private Shared lPeriodo As String
    Private Shared lSucursal As String
    Private Shared iPeriodo As cPeriodos
    Public Shared lErrorConn As String

    Private Shared Sub GetRolesByUser(ByVal Usuario As String)
        Try
            For Each dr As DataRow In cUsuariosOracle.GetRolesByUser(Usuario).Rows
                lRoles &= dr("GRANTED_ROLE").ToString.Trim.ToUpper & ","
            Next
            If lRoles.Trim.Length > 0 Then _
                lRoles = lRoles.Substring(0, lRoles.Length - 1)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Private Shared Sub GetDatosUsuario(ByVal Usuario As String)
        Try
            Dim dUser As cDatosUsuarios = New cDatosUsuarios(Usuario)
            lRestrinASede = dUser.RestringidoASede
            lRestrinAListaTDoc = dUser.RestringidoAListaTiposDoc
            lSucursal = dUser.Sede
            lEsCajero = dUser.EsCajero
            lIdCaja = dUser.Caja
            lListaTDoc = ""
            For Each TDoc As String In dUser.ListaTiposDoc.Split(",")
                lListaTDoc &= "'" & TDoc & "',"
            Next
            If lListaTDoc.Trim.Length > 0 Then _
                lListaTDoc = lListaTDoc.Substring(0, lListaTDoc.Length - 1)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public Shared ReadOnly Property EsCajero() As Boolean
        Get
            Return lEsCajero
        End Get
    End Property
    Public Shared ReadOnly Property IdCaja() As String
        Get
            Return lIdCaja
        End Get
    End Property
    Public Shared ReadOnly Property RestringidoASede() As Boolean
        Get
            Return lRestrinASede
        End Get
    End Property
    Public Shared ReadOnly Property IDSede() As String
        Get
            Return lSucursal
        End Get
    End Property
    Public Shared ReadOnly Property IDUsuario() As String
        Get
            Return lUser
        End Get
    End Property
    Public Shared ReadOnly Property RestringidoAListaTiposDoc() As Boolean
        Get
            Return lRestrinAListaTDoc
        End Get
    End Property
    Public Shared Function GetFiltroTiposDoc(ByVal Campo As String) As String
        If RestringidoAListaTiposDoc Then
            Return Campo & " IN(" & lListaTDoc & ")"
        Else
            Return ""
        End If
    End Function

    Public Shared Function GetSede() As String
        Return IDSede
    End Function

    Public Shared Function GetFiltroSede(ByVal campo As String) As String
        Return campo & " IN(" & IDSede & ")"
    End Function
    Public Shared Function Autenticar(ByVal Usuario As String, ByVal Password As String) As Boolean
        lUser = Usuario.ToUpper
        lPass = Password
        Try
            If cUsuariosOracle.IsValidUser(lUser, lPass) Then
                lIsAutenticado = True
                GetRolesByUser(lUser)
                GetDatosUsuario(lUser)
                Return lIsAutenticado
            Else
                lErrorConn = cUsuariosOracle.lErrorConn
                lIsAutenticado = False
                Return lIsAutenticado
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Function
    Public Shared ReadOnly Property UserID() As String
        Get
            Return lUser
        End Get
    End Property
    Public Shared ReadOnly Property Pass() As String
        Get
            Return lPass
        End Get
    End Property
    Public Shared ReadOnly Property IsAutenticado() As Boolean
        Get
            Return lIsAutenticado
        End Get
    End Property
    Public Shared Sub RegistroDatos(ByVal Periodo As String, ByVal Sucursal As String)
        lPeriodo = Periodo
        lSucursal = Sucursal
        Try
            iPeriodo = New cPeriodos(lPeriodo)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Shared ReadOnly Property Periodo() As cPeriodos
        Get
            Return iPeriodo
        End Get
    End Property

    Public Shared Function IsInRole(ByVal Role As String) As Boolean
        Return lRoles.IndexOf(Role.Trim.ToUpper) <> -1
    End Function

    Public Shared ReadOnly Property Roles() As String
        Get
            Return lRoles
        End Get
    End Property

End Class

Public Class cUsuariosOracle
    Public Sub New()
    End Sub
    Private Shared lUser As String = "SAMUEL"
    Private Shared lPass As String = "gl0b4lc0m"
    Public Shared lErrorConn As String = ""
    Public Shared Function GetUsuarios() As DataTable
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                'USERNAME
                cmd.CommandText = "Select * FROM dba_users where ACCOUNT_STATUS='OPEN'"
                Try
                    lConn.Open()
                    Dim dtUsers As New DataTable
                    dtUsers.Load(cmd.ExecuteReader)
                    lConn.Close()
                    Return dtUsers
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Function
    Public Shared Function GetRoles() As DataTable
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                'ROLE
                cmd.CommandText = "select * from dba_roles "
                Try
                    lConn.Open()
                    Dim dtUsers As New DataTable
                    dtUsers.Load(cmd.ExecuteReader)
                    lConn.Close()
                    Return dtUsers
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Function
    Public Shared Function GetRolesByUser(ByVal User As String) As DataTable
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "select * from dba_role_privs where GRANTEE=:PUSER "
                cmd.Parameters.Add("PUSER", OracleDbType.Varchar2).Value = User.ToUpper
                Try
                    lConn.Open()
                    Dim dtUsers As New DataTable
                    dtUsers.Load(cmd.ExecuteReader)
                    lConn.Close()
                    Return dtUsers
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Function
    Public Shared Sub AddRoleToUser(ByVal Usuario As String, ByVal Role As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "GRANT " & Role & " TO " & Usuario
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub
    Public Shared Sub DelRoleToUser(ByVal Usuario As String, ByVal Role As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "REVOKE " & Role & " FROM " & Usuario
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub
    Public Shared Function IsValidUser(ByVal User As String, ByVal Pass As String) As Boolean
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = User
        cadConn.Password = Pass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                Try
                    lConn.Open()
                    lConn.Close()
                    lErrorConn = ""
                    Return True
                Catch ex As Exception
                    lErrorConn = ex.Message
                    Return False
                End Try
            End Using
        End Using
    End Function
    Public Shared Sub CreateUser(ByVal userName As String, ByVal Pass As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "CREATE USER " & userName & " IDENTIFIED BY " & Pass
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub
    Public Shared Sub CreateRol(ByVal Rol As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "CREATE ROLE " & Rol & " NOT IDENTIFIED "
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub
    Public Shared Sub EliminaUser(ByVal UserName As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "DROP USER  " & UserName & " CASCADE"
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub
    Public Shared Sub AsignaTableSpace(ByVal Space As String, ByVal UserName As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "ALTER USER " & UserName & " DEFAULT TABLESPACE  " & Space
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub

    Public Shared Sub AsignaPerfil(ByVal Perfil As String, ByVal UserName As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "ALTER USER " & UserName & " PROFILE  " & Perfil
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub

    Public Shared Sub AsignaPermiso(ByVal User As String, ByVal Objeto As String, ByVal Permisos As String)
        Dim cadConn As OracleConnectionStringBuilder = New OracleConnectionStringBuilder(My.Settings.ConnectionString)
        cadConn.UserID = lUser
        cadConn.Password = lPass
        Using lConn = New OracleConnection(cadConn.ToString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "GRANT " & Permisos & " ON " & Objeto & " TO  " & User & ";"
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub

    Public Shared Sub RevocarPermiso(ByVal User As String, ByVal Objeto As String, ByVal Permisos As String)
        Using lConn = New OracleConnection(My.Settings.ConnectionString)
            Using cmd As OracleCommand = lConn.CreateCommand
                cmd.CommandText = "REVOKE " & Permisos & " ON " & Objeto & " TO  " & User & ";"
                Try
                    lConn.Open()
                    cmd.ExecuteNonQuery()
                    lConn.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Using
        End Using
    End Sub
End Class

Public Class cDatosUsuarios
    Public drUser As dsSeguridad.SEC_DATOSUSUARIOSRow
    Public Sub New(ByVal Usuario As String)
        Try
            Dim daDuser As New dsSeguridadTableAdapters.SEC_DATOSUSUARIOSTableAdapter
            Dim dtDUser As dsSeguridad.SEC_DATOSUSUARIOSDataTable = daDuser.GetDataByIdUser(Usuario)
            If dtDUser.Rows.Count > 0 Then
                drUser = dtDUser.Rows(0)
            Else
                Throw New Exception("Usuario no registrado en datos de usuario, favor verificar")
            End If
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
    Public ReadOnly Property IdUser() As String
        Get
            Return drUser.IDUSER
        End Get
    End Property
    Public ReadOnly Property RestringidoASede() As Boolean
        Get
            Return IIf(drUser.FILTRASEDES = "S", True, False)
        End Get
    End Property
    Public ReadOnly Property Sede() As String
        Get
            Return drUser.IDSEDE
        End Get
    End Property
    Public ReadOnly Property RestringidoAListaTiposDoc() As Boolean
        Get
            Return IIf(drUser.FILTRATIPIOSDOC = "S", True, False)
        End Get
    End Property
    Public ReadOnly Property ListaTiposDoc() As String
        Get
            Return drUser.IDLISTATIPOSDOC
        End Get
    End Property
    Public ReadOnly Property EsCajero() As Boolean
        Get
            Return IIf(drUser.ESCAJERO = "S", True, False)
        End Get
    End Property
    Public ReadOnly Property Caja() As String
        Get
            If EsCajero Then
                Return drUser.IDCAJA
            Else
                Return ""
            End If
        End Get
    End Property
End Class
Public Class cActivaSeguridad
    Public Shared Sub AseguraGridMovimi(ByVal gv As System.Windows.Forms.DataGridView)
        Try
            gv.Columns("DESCUENTO1").Visible = CustomPrincipal.IsInRole("ADMINGC")
            gv.Columns("DESCUENTO2").Visible = CustomPrincipal.IsInRole("ADMINGC")
            gv.Columns("VALORBASE").ReadOnly = Not CustomPrincipal.IsInRole("ADMINGC")
            gv.Columns("VALORIVA").ReadOnly = Not CustomPrincipal.IsInRole("ADMINGC")
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
End Class
